package com.game.service.robot;

import com.game.service.app.Utils;
import com.game.service.app.get_score.Money;
import com.game.service.app.get_score.UserLoginInfo;
import com.game.service.beans.GameMessage;
import com.game.service.beans.UserInfo;
import com.game.service.beans.game.MatchUp;
import com.game.service.beans.game.TableInfo;
import com.game.service.beans.game.Weapon;
import com.game.service.socket.SocketServer;
import com.google.gson.Gson;

import java.util.*;

import static com.game.service.define.GameDefine.*;
import static com.game.service.define.RoomConfig.*;

public class RobotMgr implements IGameMessage {
    No2Robot no2Robot;
    SocketServer mKernel;
    public static final int ALL_X = 1024;//两个玩家相对位置
    public static final int V0 = 700;//箭矢初速度
    public static final int G = -250;//重量加速度
    private boolean increasing = true;

    public RobotMgr() {
        mKernel = SocketServer.getKernel();
        no2Robot = new No2Robot();
        UserInfo userRobot = createUser();

        no2Robot.setUserInfo(userRobot);
        //  mKernel.userMap.put(1000, no2Robot.getUserInfo());
    }


    private UserInfo createUser() {
        UserInfo userRobot = new UserInfo();
        userRobot.setName("又菜又爱玩");
        userRobot.setUid(1000);
        Money money = new Money();
        money.setCoin(0);
        money.setDiamond(0);
        userRobot.setMoney(money);
        userRobot.setScore(10000000);
        userRobot.setMac(ROOM_ROBOT_MAC);

        UserLoginInfo userLoginInfo = new UserLoginInfo();
        userLoginInfo.setUser_nickname("又菜又爱玩");
        userLoginInfo.setAvatar("https://testfiles.hnthwj.com/avatar_3.png");
        userRobot.setUserLoginInfo(userLoginInfo);
        return userRobot;
    }

    public void matchUp() {
        if (!no2Robot.getUserInfo().getTableId().isEmpty()) {
            //确保这个机器人没有进入到其他桌子游戏
            return;
        }
        GameMessage<MatchUp> gameMessage = new GameMessage<>();
        MatchUp matchUp = new MatchUp();
        UserInfo userRobot = no2Robot.getUserInfo();
        matchUp.setUid(userRobot.getUid());
        gameMessage.setCmd(matchUp);
        String json = new Gson().toJson(gameMessage);
        mKernel.matchUp(json);
    }

    public void autoWeapon(int index) {
        GameMessage<UserInfo> gameMessage = new GameMessage<>();
        UserInfo userRobot = no2Robot.getUserInfo();

        //这里的武器信息需要另外一个系统根据，双方的状态来输出。
        Weapon weapon = new Weapon();
        weapon.force = 0.4f + index * 0.1f;
        weapon.angle = 120 + index;
        weapon.status = 0;
        //  System.out.println("angle=" + weapon.angle);
        userRobot.setWeapon(weapon);
        gameMessage.setCmd(userRobot);
        String json = new Gson().toJson(gameMessage);
        mKernel.matchWeaponUpdate(json);
    }

    public void matchWeaponUpdate(ArrayList<Float> angleList) {

        int size = angleList.size();
        int random = new Random().nextInt(size);
        GameMessage<UserInfo> gameMessage = new GameMessage<>();
        UserInfo userRobot = no2Robot.getUserInfo();

        //这里的武器信息需要另外一个系统根据，双方的状态来输出。
        Weapon weapon = new Weapon();
        weapon.force = 1;
        weapon.angle = angleList.get(random);
        weapon.status = 1;

        userRobot.setWeapon(weapon);
        gameMessage.setCmd(userRobot);
        String json = new Gson().toJson(gameMessage);
        mKernel.matchWeaponUpdate(json);
    }

    boolean isAutoGame = false;

    public void autoGame(TableInfo tableInfo) {

        if (isAutoGame) {
            return;
        }
        isAutoGame = true;
        //1.先生成命中角度
        float AY = tableInfo.getPlayerInfoA().getuPos().getY();
        float BY = tableInfo.getPlayerInfoB().getuPos().getY();
        ArrayList<Float> angleList = createAngle(AY, BY);

        //2.定时执行发射角度
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if (tableInfo.getMatchDuration() < MATCH_DURATION) {
                    //  matchWeaponUpdate(angleList);
                }
            }
        };
        timer.schedule(timerTask, 1000, 3000);
        //=============================================
//        ArrayList<Float> angleListWeapon = new ArrayList<>();
//        for (int i = 0; i < 60; i++) {
//            angleListWeapon.add(90 + i * 1.5f);
//        }

        Timer timer2 = new Timer();
        TimerTask timerTaskWeapon = new TimerTask() {
            @Override
            public void run() {
                if (tableInfo.getWinner() != TableInfo.TableState.Destroy.ordinal() && tableInfo.getMatchDuration() == MATCH_DURATION) {
                    //出了结果，比赛时间为MATCH_DURATION,
                    timer2.cancel();
                    timer.cancel();
                }
                if (tableInfo.getMatchDuration() < MATCH_DURATION) {
                    if (increasing) {
                        index++;
                        if (index == 60) {
                            increasing = false;
                        }
                    } else {
                        index--;
                        if (index == 0) {
                            increasing = true;
                        }
                    }

                    autoWeapon(index);
                }
            }
        };
        timer2.schedule(timerTaskWeapon, 1000, 50);

    }

    int index = 0;

    public void reset() {
        isAutoGame = false;
    }

//    public static void main(String[] args) {
//
//        // autoGame(null);
//        for (int i = 0; i < 100; i++) {
//            int a = new Random().nextInt(20);
//            System.out.println("随机" + a);
//        }
//
//
//    }

    public ArrayList<Float> createAngle(float AY, float BY) {
        ArrayList<Float> angleList = new ArrayList<>();
        //B点作为原点，高度为A-B
        //宽度为负数方向
        //———————————A(-1024,AY)———————————————————————————————————B(0,BY)————————————————————————————
        //人物模型数据
        //-------抛物原点坐标(0,24),全部为100,头(50~26)躯干(26~-10)脚(-10~-50)


        int absX = -ALL_X;
        float absY = AY - BY;
        float angle = 0;
        int i = 0;
        while (true) {
            double radian = Math.PI / 180 * angle;//角度转弧度//需要求的弧度
            double v0_x = V0 * Math.cos(radian);//x轴速度
            double v0_y = V0 * Math.sin(radian);//yz轴速度
            double t = absX / v0_x;//x轴位移1000计算出时间t，由时间t计算出y的位置，根据y的值不同确定命中的部位
            double dy = 24 + v0_y * t + 0.5 * G * t * t;//y轴位移
            angle += 0.2f;

            if (angle >= 180) {
                break;
            }
            //不超出屏幕，在腿部区域以上，在头部区域一下
            if (v0_y * t < 350 && dy > absY + 26 && dy <= absY + 50) {
                System.out.println(i + "命中-头部区域角度:" + angle);
                i++;
                angleList.add(angle);
            }
            if (v0_y * t < 350 && dy > absY - 10 && dy <= absY + 26) {
                System.out.println(i + "命中-中间区域角度:" + angle);
                i++;
                angleList.add(angle);
            }

            if (v0_y * t < 350 && dy > absY - 50 && dy <= absY - 10) {
                System.out.println(i + "命中-腿部区域角度:" + angle);
                i++;
                angleList.add(angle);
            }

        }
        return angleList;
    }

    public void matchAgain() {
        GameMessage<MatchUp> gameMessage = new GameMessage<>();
        MatchUp matchUp = new MatchUp();
        UserInfo userRobot = no2Robot.getUserInfo();
        matchUp.setUid(userRobot.getUid());
        matchUp.setTableId(userRobot.getTableId());
        gameMessage.setCmd(matchUp);
        String json = new Gson().toJson(gameMessage);
        mKernel.matchAgain(json);
    }


    @Override
    public void send(int main, int sub, Object obj) {
        //  System.out.printf("RobotMgr:%s-%s", main, sub);
        switch (sub) {
            case GAME_C_SUB_MATCH_WEAPON_RETURN:
                // System.out.println("RobotMgr:GAME_C_SUB_MATCH_WEAPON_RETURN");
                // sendToSpectatorWeapon((TableInfo) obj);
                break;

            case GAME_C_SUB_MATCH_UP_RETURN://游戏房间信息
                //  System.out.println("RobotMgr:GAME_C_SUB_MATCH_UP_RETURN");
                TableInfo table = (TableInfo) obj;


                break;
            case GAME_C_SUB_MATCH_HIT_RETURN://击中返回
                // System.out.println("RobotMgr:GAME_C_SUB_MATCH_HIT_RETURN");
                TableInfo tableMatchHit = (TableInfo) obj;
                break;

            case GAME_C_SUB_MATCH_GAME_START_RETURN://
                // System.out.println("RobotMgr:GAME_C_SUB_MATCH_GAME_START_RETURN");
                //游戏开始
                TableInfo tableStart = (TableInfo) obj;
                if (isRobotTable(tableStart, no2Robot.getUserInfo())) {
                    //只处理机器人所在的桌子。
                    autoGame(tableStart);//AI自动开始
                }
                break;

            case GAME_C_SUB_MATCH_CREATE_TABLE_RETURN://创建房间成功
                //  System.out.println("RobotMgr:GAME_C_SUB_MATCH_CREATE_TABLE_RETURN");
                TableInfo tableCreate = (TableInfo) obj;
                if (tableCreate != null) {
                    //创建了桌子信息,延时安排机器人进入
                    new Thread(() -> {
                        try {
                            Thread.sleep(Utils.random(3, 10) * 1000L);
                            matchUp();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }).start();
                }
                break;
            case GAME_C_SUB_MATCH_OVER_RETURN:
                // System.out.println("RobotMgr:GAME_C_SUB_MATCH_OVER_RETURN");
                TableInfo tableOver = (TableInfo) obj;
//                if (isRobotTable(tableOver, no2Robot.getUserInfo())) {
//                    //比赛结束
//                    reset();
//                    if (tableOver.getPlayerInfoB().getPrepare() == 1) {
//                        new Thread(() -> {
//                            try {
//                                Thread.sleep(Utils.random(1, 5) * 1000L);
//                                matchAgain();
//                            } catch (InterruptedException e) {
//                                throw new RuntimeException(e);
//                            }
//                        }).start();
//
//                    }
//                }
                break;

            case GAME_C_SUB_MATCH_AGAIN_RETURN: //收到对方玩家准备决战到底
                //   System.out.println("RobotMgr:GAME_C_SUB_MATCH_AGAIN_RETURN");
                TableInfo tableAgain = (TableInfo) obj;
                if (isRobotTable(tableAgain, no2Robot.getUserInfo())) {
                    //自己没有准备的时候发送决战到底
                    if (tableAgain.getPlayerInfoB().getPrepare() == UserInfo.UNPREPARED) {
                        new Thread(() -> {
                            try {
                                Thread.sleep(Utils.random(1, 5) * 1000L);
                                matchAgain();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }).start();

                    }
                }
                break;

            default:
                break;
        }
    }

    public boolean isRobotTable(TableInfo table, UserInfo userRobot) {

        return table != null && userRobot.getTableId() == table.getTableId();
    }


}
